package com.rzjm.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.TempProjectDao;
import com.rzjm.api.dao.TempProjectRecordDao;
import com.rzjm.api.dao.TempProjectUserDao;
import com.rzjm.api.entity.*;
import com.rzjm.api.exception.TransactionalException;
import com.rzjm.api.service.TempProjectRecordService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class TempProjectRecordServiceImpl extends BaseServiceImpl<TempProjectRecordDao, TempProjectRecord> implements TempProjectRecordService {

    @Resource
    private TempProjectRecordDao recordDao;
    @Resource
    private TempProjectUserDao tempProjectUserDao;

    @Value("${web.imgprefix}")
    private String imgprefix;//图片地址

    @Override
    public List<TempProjectRecord> getListBySysUserId(User user, Integer page, Integer pageSize) {
        QueryWrapper<TempProjectRecord> qw = new QueryWrapper<>();
        qw.eq("send_user_id",user.getId());
        List<TempProjectRecord> list = recordDao.getPageEntityList(qw,page,pageSize);
        list.forEach(record -> {
            List<String> imgUrls = new ArrayList<>();
            if(StrUtil.isNotEmpty(record.getImgs())){
                String[] imgs = record.getImgs().split(",");
                if(imgs!=null){
                    for (String img : imgs){
                        imgUrls.add(imgprefix + img);
                    }
                }
                record.setImgUrls(imgUrls);
            }
        });
        return list;
    }

    @Override
    @Transactional
    public int addRecord(TempProjectRecord record, Integer is_over, TempProjectUser tempProjectUser,boolean blIsHasThisPro) throws TransactionalException {
        try{
            if(is_over == 1){
                tempProjectUser.setState(4);
            }
            int ret = 0;
            if(blIsHasThisPro){
                ret = tempProjectUserDao.updateById(tempProjectUser);
                if(ret <= 0){
                    throw new TransactionalException("recordDao insert error");
                }
            }else{
                ret = tempProjectUserDao.insert(tempProjectUser);
                if(ret <= 0){
                    throw new TransactionalException("recordDao insert error");
                }
            }
            record.setUserProId(tempProjectUser.getId());
            ret = recordDao.insert(record);
            if(ret <= 0){
                throw new TransactionalException("recordDao insert error");
            }
            return  1;
        }catch (Exception e){
            throw new TransactionalException("addRecord system error");
        }
    }
}
